using MediatR;
using Microsoft.EntityFrameworkCore;
using Work.API.Applications.Read.Commands;
using Work.Domain;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 按卡号查询患者处理器
    /// </summary>
    public class GetPatientByCardQueryHandler : IRequestHandler<GetPatientByCardQuery, ApiResult<Patient?>>
    {
        private readonly IBaseRepository<Patient> _patientRepo;

        public GetPatientByCardQueryHandler(IBaseRepository<Patient> patientRepo)
        {
            _patientRepo = patientRepo;
        }

        public async Task<ApiResult<Patient?>> Handle(GetPatientByCardQuery request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<Patient?>();
            var patient = await _patientRepo.DB.Set<Patient>()
                .AsNoTracking()
                .FirstOrDefaultAsync(x => x.CardNumber == request.CardNumber, cancellationToken);
            if (patient == null)
            {
                result.Code = ApiEnum.失败;
                result.Message = "请先办理就诊卡";
                result.Data = null;
                return result;
            }

            result.Code = ApiEnum.成功;
            result.Message = ApiEnum.成功.ToString();
            result.Data = patient;
            return result;
        }
    }
}











